package configure

import (
	"fmt"
	"gitee.com/theegg/go-brick/app/model/system/system_configures"
	"strings"
)

// @title Value
// @description 获取值
func Value(sign string, options ...string) (interface{}, error) {
	defaultValue := ""
	if len(options) > 0 && options[0] != "" {
		defaultValue = options[0]
	}

	item, err := system_configures.GetItemBySignFromCache(sign)
	if err != nil {
		if defaultValue != "" {
			return defaultValue, nil
		}
		return nil, err
	}

	configureItem := system_configures.GetConfigureTypeItem(item.ConfigureType)
	if configureItem == nil {
		return nil, fmt.Errorf("对不起, 无效的类型")
	}

	switch item.ConfigureType {
	case "string":
		return item.Value, nil
	case "bool":
		if item.Value == "0" {
			return false, nil
		} else {
			return true, nil
		}
	case "array_1":
		fallthrough
	case "array_2":
		fallthrough
	case "array_3":
		return BuildArray(item.Value, configureItem["separator"]), nil
	case "int":
		return item.Value, nil
	}

	return nil, fmt.Errorf("对不起, 不存在的类型")
}

// 构建一个[]string
func BuildArray(value string, separator string) []string {
	return strings.Split(value, separator)
}
